<template>
  <div class="container">
    <h1>Incident Pick Up</h1>
    
    <!-- 搜索框 -->
    <div class="search-container">
      <input v-model="searchTerm" placeholder="搜索 Inc_id" />
      <input v-model="searchOpenedBy" placeholder="搜索 Opened By" />
      <input v-model="searchPriority" placeholder="搜索 Priority" />
      <input v-model="searchProject" placeholder="搜索 Project" />
      <input v-model="searchShortDescription" placeholder="搜索 Short Description" />
      <input v-model="searchAssignmentGroup" placeholder="搜索 Assignment Group" />
    </div>
    
    <!-- 表格 -->
    <table>
      <thead>
        <tr>
          <th>Inc_id</th>
          <th>Opened</th>
          <th>Resolved</th>
          <th>Opened By</th>
          <th>Priority</th>
          <th>Project</th>
          <th>Short Description</th>
          <th>Description</th>
          <th>Assigned To</th>
          <th>Assignment Group</th>
          <th>Incident State</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="incident in paginatedIncidents" :key="incident.id">
          <td @click="goToDetail(incident.Inc_id)" class="clickable">{{ incident.Inc_id }}</td>
          <td>{{ formatDate(incident.Opened) }}</td>
          <td>{{ formatDate(incident.Resolved) }}</td>
          <td>{{ incident.Opened_by }}</td>
          <td>{{ incident.Priority }}</td>
          <td>{{ incident.Project }}</td>
          <td>
            <span @click="toggleFullDescription(incident.id, 'shortDescription')" class="description-text">
              {{ getSubstring(incident.Short_description, 15) }}<span v-if="fullDescriptionId === incident.id && fullDescriptionType === 'shortDescription'">...{{ incident.Short_description }}</span>
            </span>
          </td>
          <td>
            <span @click="toggleFullDescription(incident.id, 'description')" class="description-text">
              {{ getSubstring(incident.Description, 15) }}<span v-if="fullDescriptionId === incident.id && fullDescriptionType === 'description'">...{{ incident.Description }}</span>
            </span>
          </td>
          <td>{{ incident.Assigned_to }}</td>
          <td>{{ incident.Assignment_group }}</td>
          <td>{{ incident.Incident_state }}</td>
        </tr>
      </tbody>
    </table>
    
    <!-- 分页 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页，共 {{ total }} 条</span>
      <button @click="nextPage" :disabled="currentPage * limit >= total">下一页</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';

export default {
  setup() {
    const incidents = ref([]); // 所有工单数据
    const total = ref(0);
    const currentPage = ref(1);
    const limit = ref(10);
    const searchTerm = ref('');
    const searchOpenedBy = ref('');
    const searchPriority = ref('');
    const searchProject = ref('');
    const searchShortDescription = ref('');
    const searchAssignmentGroup = ref('');
    const router = useRouter();
    const fullDescriptionId = ref(null);
    const fullDescriptionType = ref(null);

    // 获取所有工单数据
    const fetchIncidents = async () => {
      try {
        const response = await axios.get('http://localhost:3000/api/incidents', {
          params: {
            limit: 1000000 // 获取最多 1000000 条数据
          }
        });
        incidents.value = response.data.incidents;
        console.log('API 返回的数据:', incidents.value.map(incident => ({
          Inc_id: incident.Inc_id,
          Assigned_to: incident.Assigned_to,
          Incident_state: incident.Incident_state
        }))); // 调试日志
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    // 筛选工单
    // 筛选工单
const filteredIncidents = computed(() => {
    let result = incidents.value.filter(incident => 
        (!incident.Assigned_to || incident.Assigned_to.trim() === '') // assignedTo 为空
    );

    // 根据搜索条件进一步筛选
    if (searchTerm.value) {
        result = result.filter(incident => 
            incident.Inc_id.toLowerCase().includes(searchTerm.value.toLowerCase())
        );
    }
    if (searchOpenedBy.value) {
        result = result.filter(incident => 
            incident.Opened_by.toLowerCase().includes(searchOpenedBy.value.toLowerCase())
        );
    }
    if (searchPriority.value) {
        result = result.filter(incident => 
            incident.Priority.toLowerCase().includes(searchPriority.value.toLowerCase())
        );
    }
    if (searchProject.value) {
        result = result.filter(incident => 
            incident.Project.toLowerCase().includes(searchProject.value.toLowerCase())
        );
    }
    if (searchShortDescription.value) {
        result = result.filter(incident => 
            incident.Short_description.toLowerCase().includes(searchShortDescription.value.toLowerCase())
        );
    }
    if (searchAssignmentGroup.value) {
        result = result.filter(incident => 
            incident.Assignment_group.toLowerCase().includes(searchAssignmentGroup.value.toLowerCase())
        );
    }

    // 新增条件：incidentState 不为 Closed 或 Resolved
    result = result.filter(incident => 
        !['Closed', 'Resolved'].includes(incident.Incident_state)
    );

    console.log('筛选后的数据:', result); // 调试日志
    total.value = result.length; // 更新总条数
    return result;
});

    // 分页数据
    const paginatedIncidents = computed(() => {
      const start = (currentPage.value - 1) * limit.value;
      const end = start + limit.value;
      return filteredIncidents.value.slice(start, end);
    });

    // 分页逻辑
    const nextPage = () => {
      if (currentPage.value * limit.value < total.value) {
        currentPage.value++;
      }
    };

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };

    // 跳转到详情页
    const goToDetail = (incId) => {
      router.push({ name: 'IncidentDetailforPickUp', params: { incId } });
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    };

    // 展开/收起描述
    const toggleFullDescription = (id, type) => {
      fullDescriptionId.value = fullDescriptionId.value === id && fullDescriptionType.value === type ? null : id;
      fullDescriptionType.value = type;
    };

    // 截取字符串
    const getSubstring = (str, length) => {
      if (!str) return ''; // 如果字符串为空或 undefined，返回空字符串
      return str.substring(0, length);
    };

    // 初始化加载数据
    fetchIncidents();

    return {
      incidents,
      total,
      currentPage,
      limit,
      searchTerm,
      searchOpenedBy,
      searchPriority,
      searchProject,
      searchShortDescription,
      searchAssignmentGroup,
      filteredIncidents,
      paginatedIncidents,
      fetchIncidents,
      nextPage,
      prevPage,
      goToDetail,
      formatDate,
      toggleFullDescription,
      fullDescriptionId,
      fullDescriptionType,
      getSubstring
    };
  }
};
</script>

<style scoped>
.container {
  max-width: 1500px;
  padding: 10px;
  margin-bottom: 150px;
  background-color: white; /* 白色背景 */
  border-radius: 10px; /* 圆角 */
  padding: 20px; /* 内边距 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

h1 {
  margin-top: 10px;
  margin-bottom: 10px;
}

.search-container {
  margin-bottom: 20px;
}

.search-container input {
  margin-right: 10px;
  width: 130px;
  border-radius: 4px; /* 添加圆角 */
  border: 1px solid #ccc;
  padding: 8px; /* 增加内边距 */
  transition: border-color 0.3s; /* 添加过渡效果 */
}

.search-container input:hover {
  border-color: #007bff; /* 悬停时边框颜色 */
}

table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

table th, table td {
  border: 1px solid #ddd;
  padding: 4px;
}

.clickable {
  color: blue; /* 保留 Inc_id 列的蓝色样式 */
  cursor: pointer;
}

.description-text {
  cursor: pointer; /* 仅显示指针样式，不改变颜色 */
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center; /* 居中对齐 */
  align-items: center;
}

.pagination button {
  background-color: #007bff; /* 蓝色背景 */
  color: white; /* 白色文字 */
  border: none;
  border-radius: 4px; /* 添加圆角 */
  padding: 8px 16px; /* 增加内边距 */
  margin: 0 10px; /* 增加按钮间距 */
  cursor: pointer;
  transition: background-color 0.3s; /* 添加过渡效果 */
}

.pagination button:hover {
  background-color: #0056b3; /* 悬停时深蓝色背景 */
}

.pagination button:disabled {
  background-color: #ccc; /* 禁用状态的灰色背景 */
  cursor: not-allowed;
}
</style>